package fun.eliauk.treedemo.utils.encrypt;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.List;


@ConditionalOnProperty(value = "qqzj.encrypt", havingValue = "aes-test")
@Service
public class AESTestEncryptService implements EncryptService{

    // key：AES模式下，key必须为16位
    @Value("${qqzj.aes-key}")
    static String  KEY;
    // iv：偏移量，ECB模式不需要，CBC模式下必须为16位
    @Value("${qqzj.aes-iv}")
    static String IV;

    @Override
    public String encrypt(String content) {
        String encryptStr = "";
        List<String> textList = TextUtil.text2Slice(content, 4);

        // 分段加密
        for (String text : textList) {
            String s = aesEncrypt(text);
            encryptStr += s;
        }
        return encryptStr;
    }

    @Override
    public String decrypt(String content) {
        // 经过测试，aes算法得到密文在再经过base64编码得到的每段是24个字符
        List<String> textList = TextUtil.text2Group(content, 24);

        //分段解密
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < textList.size()-1; i++) {
            String s = aesDecrypt(textList.get(i));
            //分段拼接 每段解密出来只取第一个字符
            sb.append(s.charAt(0));
        }
        //最后一段取全部字符
        String lastStr = aesDecrypt(textList.get(textList.size() - 1));
        sb.append(lastStr);

        // 分段解密
        return sb.toString();
    }

    private static  String aesEncrypt(String content){
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, KEY.getBytes(), IV.getBytes());
        //加密后转Base64编码
        String encrypt = aes.encryptBase64(content);
        return encrypt;
    }

    private static String aesDecrypt(String content){
        //Base64 解码后 解密
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, KEY.getBytes(), IV.getBytes());
        String decrypt = aes.decryptStr(Base64.decode(content));
        return decrypt;
    }

//    public static void main(String[] args) {
//        String text1 = "青青";
//        String text2 = "子衿";
//        String s1 = aesEncrypt(text1);
//        String s2 = aesEncrypt(text2);
//
//        System.out.println(s1);
//        System.out.println(aesDecrypt(s1));
//        System.out.println(s2);
//        System.out.println(aesDecrypt(s2));
//
//        System.out.println(aesDecrypt(s1+s2));
//
//    }

    public static void main(String[] args) {
        String text1 = "1881";
        System.out.println(aesEncrypt(text1));
    }
}
